package com.smartleanx.module.hrm.framework.web;

import com.smartleanx.framework.common.pojo.CommonResult;
import com.smartleanx.framework.common.util.servlet.ServletUtils;
import com.smartleanx.framework.security.core.util.SecurityFrameworkUtils;
import com.smartleanx.framework.web.config.WebProperties;
import com.smartleanx.framework.web.core.filter.ApiRequestFilter;
import com.smartleanx.module.hrm.context.EmployeeContextHolder;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.enums.ErrorCodeConstants;
import com.smartleanx.module.hrm.service.employee.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 获取员工id
 *
 * @author tengcj
 * @since 2024/5/23
 */
@Slf4j
public class EmployeeContextWebFilter extends ApiRequestFilter {

    private final EmployeeService employeeService;

    public EmployeeContextWebFilter(WebProperties webProperties, EmployeeService employeeService) {
        super(webProperties);
        this.employeeService = employeeService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        EmployeeDO employee = employeeService.getEmployeeByUserId(loginUserId);
//         if (employee == null) {
//             log.error("[doFilterInternal][用户({}) 没有员工信息]", loginUserId);
//             ServletUtils.writeJSON(response, CommonResult.error(ErrorCodeConstants.EMPLOYEE_NOT_EXISTS));
//             return;
//         }
        if (employee != null) {
            EmployeeContextHolder.setEmployeeId(employee.getId());
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            EmployeeContextHolder.clear();
        }
    }
}
